/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClientChooserDialog.java
 *
 * Created on 9.5.2011, 12:57:17
 */
package GUI;

import Model.BorrowManagerImpl;
import Model.Client;
import Model.ClientManagerImpl;
import Model.Medium;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author pyty
 */
public class ClientChooserDialog extends javax.swing.JDialog {
    
    ClientTableModel clientListModel;
    MediumActionDialog parent;
    
    private Medium medium = null;
    private LoadClientsSwingWorker loadClientsSwingWorker;

    ClientManagerImpl clientManager = new ClientManagerImpl();

    void setMedium(Medium medium) {
        this.medium = medium;
    }
    
    void setParent(MediumActionDialog parent) {
        this.parent = parent;
    }
 
    private class LoadClientsSwingWorker extends SwingWorker<List<Client>,Void> {

        private String searchString = null;
        
        @Override    
        protected List<Client> doInBackground() throws Exception {
            
            try {
                DataSource ds = MainFrame.prepareDataSource();
                clientManager.setDataSource(ds);
                List<Client> clients;
                if(searchString == null) {
                    clients = clientManager.findAllClients();
                } else {
                    clients = clientManager.searchClientsByString(searchString);
                }
                return clients;
                
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                List<Client> clients = get();
            
                for(Client c : clients) {
                    if (c.getBlackListed().equals("no")){
                    clientListModel.addClient(c);
                    }
                }
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }  
        
        public void setSearchString(String s) {
            this.searchString = s;
        }
    }

    /** Creates new form ClientChooserDialog */
    public ClientChooserDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        clientListModel = (ClientTableModel) jTable1.getModel();
 
        loadClientsSwingWorker = new LoadClientsSwingWorker();
        loadClientsSwingWorker.execute();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToggleButton1 = new javax.swing.JToggleButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        jToggleButton1.setText("jToggleButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/texts"); // NOI18N
        setTitle(bundle.getString("chooseClient")); // NOI18N
        setBounds(new java.awt.Rectangle(300, 300, 0, 0));

        jButton1.setText(bundle.getString("chooseClient")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new ClientTableModel());
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(509, 509, 509))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jTable1.getSelectedRowCount() != 0 ) {
            Client client = clientListModel.getValueAt(jTable1.getSelectedRow());
            BorrowManagerImpl borrowManager = new BorrowManagerImpl();
            try {
                borrowManager.setDataSource(MainFrame.prepareDataSource());
            } catch (SQLException ex) {
                Logger.getLogger(MediumActionDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                borrowManager.borrowMedium(client, medium);
                parent.disableButton();
                this.setVisible(false);
            } catch (IllegalArgumentException iae) {
                JOptionPane.showMessageDialog(null, RBUtils.getBoundle("error-mediumAlreadyBorrowed"));
            }
        } else {
            JOptionPane.showMessageDialog(null, RBUtils.getBoundle("mustChooseClient"));
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ClientChooserDialog dialog = new ClientChooserDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
}
